package com.woniuxy.thirdfactory;

import com.woniuxy.firstfactory.Person;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;

/**
 * @Author: 马宇航
 * @Todo: 新增第三个工厂模式，直接去配置文件中获取了
 * @DateTime: 22/03/23/0023 下午 2:25
 * @Component: 成都蜗牛学苑
 **/
public class MarkPersonFactoryThree {
    /**
     * 第三类工厂 ，直接通过配置，来实例化对象
     * @return
     */
    public Person doMakePerson(){
        //1.读取配置文件 Properties加载properties配置文件的
        Properties properties = new Properties();
        //2.读取配置文件
        InputStream resourceAsStream = MarkPersonFactoryThree.class.getClassLoader().getResourceAsStream("person.properties");
        try {
            properties.load(resourceAsStream);
            //方法一
            Enumeration<?> enumeration = properties.propertyNames();
            while (enumeration.hasMoreElements()) {
                System.out.println(enumeration.nextElement());
            }
            //方法二
            Set<String> strings = properties.stringPropertyNames();

            //3.获取里面的value
            String fullyQualifiedClassName = properties.getProperty("person");
        //4.通过反射创建对应的对象
            Class<?> aClass = Class.forName(fullyQualifiedClassName);
            return (Person) aClass.newInstance();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
